//app.js
App({
  onLaunch: function () {
    // 登录
    this.login();
  },

  login : function () {
    var that  = this;

    if (wx.getStorageSync('code_secret_key')) {
      // 获取用户信息
      wx.request({
        url: 'https://miniapp.okaoyan.com/api/v1/user/info',
        header: {
          SessionKey: wx.getStorageSync('code_secret_key')
        },
        success(res) {
          that.globalData.userInfo = res.data.data;
          if (that.userInfoReadyCallback) {
            that.userInfoReadyCallback(res.data.data)
          }  
        }
      })
      return;
    }

    wx.login({
      success: res => {
        wx.request({
          url: "https://miniapp.okaoyan.com/api/v1/login/get_session_key",
          data: {code: res.code},
          success (res) {
            // 保存
            var session_key = res.data.data.session_key;
            wx.setStorage({
              key: 'code_secret_key',
              data: session_key,
            })

            // 保存用户信息
            wx.getUserInfo({
              success: res => {
                that.sendUserInfo(res);
              }
            })
          }
        })
      }
    })
  },

  sendUserInfo(userdata) {
    var that = this;
    wx.request({
      url: "https://miniapp.okaoyan.com/api/v1/login/save_user_info",
      data: {
        session_key: wx.getStorageSync('code_secret_key'),
        raw_data: userdata.rawData,
        signature: userdata.signature,
        iv: userdata.iv,
        encrypted_data: userdata.encryptedData
      },
      success(res) {
        that.globalData.userInfo = res.data.data;
        if (that.userInfoReadyCallback) {
          that.userInfoReadyCallback(res.data.data)
        } 
      }
    })
  },
  globalData: {
    userInfo: null
  }
})